<template>
  <div class="content">
    <!--头部-->
    <div class="header-setting" :style="expendStyle">
      <a-breadcrumb class="breadcrumb">
        <a-breadcrumb-item>
          <a href="../main">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>财务管理</a-breadcrumb-item>
        <a-breadcrumb-item>电子发票</a-breadcrumb-item>
      </a-breadcrumb>
      <!--查询条件-->
      <div class="box-condition-body">
        <div class="box-condition-item">
          <div style="margin: 0 50px">开票时间</div>
          <template>
            <div class="button_time">
              <a-button
                type="primary"
                @click="button_time(0)"
                :style="computedStyle(0)"
                >今天</a-button
              >
              <a-button
                type="primary"
                @click="button_time(1)"
                :style="computedStyle(1)"
                >昨天</a-button
              >
              <a-button
                type="primary"
                @click="button_time(2)"
                :style="computedStyle(2)"
                >本周</a-button
              >
              <a-button
                type="primary"
                @click="button_time(3)"
                :style="computedStyle(3)"
                >上周</a-button
              >
              <a-button
                type="primary"
                @click="button_time(4)"
                :style="computedStyle(4)"
                >本月</a-button
              >
            </div>
          </template>
          <template>
            <div style="margin: auto 50px">
              <a-range-picker
                :showTime="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                @ok="onOk"
                @change="onChange"
                :value="rangePicker()"
              />
            </div>
          </template>
        </div>
        <div class="box-condition-item">
          <div style="margin: 0 50px">停车点</div>
          <template>
            <a-select
              style="margin: 0 100px 0 16px; width: 200px"
              showSearch
              mode="multiple"
              placeholder="选择停车点"
              optionFilterProp="children"
              v-model="selectParkId"
              @change="selectParkChange"
              :allowClear="true"
            >
              <a-select-option v-for="p in parks" :key="p.id" :value="p.id"
                >{{ p.parkName }}
              </a-select-option>
            </a-select>
          </template>
          <div style="margin: 0px 20px 0 50px">发票号码</div>
          <template>
            <a-input
              style="margin: 0px 20px 0 0px; width: 200px"
              v-model="invoiceNo"
              @change="delayedTime"
              placeholder="发票号码"
            />
          </template>
          <a-button icon="sync" style="margin: 0 0 0 20px" @click="reset"
            >重置</a-button
          >
        </div>
        <!-- <div class="box-condition-item">
                    <div style="margin: 0 50px">
                    </div>
                </div> -->
        <div class="box-expand" @click="switchExpend">
          点击{{ isExpand ? "收起" : "展开" }}
        </div>
      </div>
    </div>

    <!-- 表单 -->
    <div class="box-form">
      <!--工具栏-->
      <div class="box-tool">
        <div></div>
        <div style="display: flex">
          <a-button type="primary" @click="exportExcel" icon="download"
            >导出记录</a-button
          >
        </div>
      </div>
      <!--数据表格-->
      <div class="box-table">
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          @change="tableChange"
          bordered
          size="small"
          :scroll="scroll"
          :customRow="customRow"
          :rowClassName="setRowClassName"
        >
          <!-- 脚步 -->
          <template slot="propertyDetail" slot-scope="text">
            <div>{{ text == 1 ? "个人" : "企业" }}</div>
          </template>
          <template slot="url" slot-scope="text">
            <div>
              <a :href="text" target="_blank">{{ text }}</a>
            </div>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 弹窗  @ok="handleOk" @cancel="cancel"-->
    <!-- <a-modal title="发票图片" v-model="correctPopupData.visible" :width="980"
         @cancel="cancelCorrect" :confirmLoading="correctPopupData.loading">
            <div class="box-correction-popup">
                <a-carousel class="box-image" autoplay>
                    <template v-for="image in correctPopupData.imageList">
                    
                        <img :key="image" :src="image" class="icon-image"/>
                   </template>
                </a-carousel>
            </div>
        </a-modal> -->
  </div>
</template>

<script>
// import Constant from '../../utils/Constant';
import moment from "moment";
import CommonApi from "../../api/CommonApi";
import Invoice from "../../api/bill/invoice";
import pdf from "vue-pdf";
import invoice from "../../api/bill/invoice";
// import ParkingRecordApi from '../../api/charge/ChargeDetail';

const columns = [
  {
    title: "发票流水",
    dataIndex: "serialNo",
    width: "10%",
  },
  {
    title: "发票号码",
    dataIndex: "orderNo",
    width: "8%",
  },
  {
    title: "发票抬头",
    dataIndex: "taxName",
    width: "10%",
  },
  {
    title: "发票性质",
    dataIndex: "property",
    width: "5%",
    scopedSlots: { customRender: "propertyDetail" },
  },
  {
    title: "开票时间",
    dataIndex: "invoiceTime",
    width: "10%",
  },
  {
    title: "不含税金额",
    dataIndex: "exTaxAmount",
    width: "8%",
  },
  {
    title: "税费金额",
    dataIndex: "taxAmount",
    width: "5%",
  },
  {
    title: "总金额",
    dataIndex: "orderAmount",
    width: "5%",
  },
  {
    title: "发票地址",
    dataIndex: "pdfUrl",
    // , width: '15%',
    scopedSlots: { customRender: "url" },
  },
];

const dataSource = [];

const queryCondition = {
  startTimeStamp: "",
  endTimeStamp: "",
  timeScreenCondition: 6,
  limit: "100",
  curr: "1",
  //多停点list
  pID: [],
  invoiceNo: "",
};

export default {
  components: [pdf],
  name: "invoice",

  /*数据层*/
  data() {
    return {
      isExpand: true,
      parks: [],
      selectParkId: [],
      selectId: -1,
      momentArr: [],
      columns: columns,

      dataSource: dataSource,
      /*分页插件*/
      pagination: {
        showTotal: (total) => `共${total}条`,
        total: 0,
        current: 1,
        defaultCurrent: 1,
        showQuickJumper: true,
        defaultPageSize: 100,
      },
      /*表格固定头部*/
      scroll: {
        y: 550,
      },
      tableState: {
        rowId: -1,
      },
      /*当前选中的行数据*/
      currRowData: "",
      queryCondition,

      /* 修正弹窗 */
      correctPopupData: {
        visible: false,
        loading: false,
        // id: "",
        imageList: [],
      },
      time: "",
      invoiceNo: "",
    };
  },

  /*方法层*/
  methods: {
    /**表格**/
    tableChange(page) {
      this.queryCondition.curr = page.current;
      this.queryData();
      this.queryCondition.curr = 0;
    },
    /*时间按钮控制*/
    button_time(e) {
      this.selectId = e;
      let momentStart;
      let momentEnd;
      switch (e) {
        case 0:
          momentStart = moment().startOf("day");
          momentEnd = moment().endOf("day");
          break;
        case 1:
          momentStart = moment().add("day", -1).startOf("day");
          momentEnd = moment().add("day", -1).endOf("day");
          break;
        case 2:
          momentStart = moment().week(moment().week()).startOf("week");
          momentEnd = moment().week(moment().week()).endOf("week");
          break;

        case 3:
          momentStart = moment()
            .week(moment().week() - 1)
            .startOf("week");
          momentEnd = moment()
            .week(moment().week() - 1)
            .endOf("week");
          break;
        case 4:
          momentStart = moment().month(moment().month()).startOf("month");
          momentEnd = moment().month(moment().month()).endOf("month");
          break;
        default:
          break;
      }
      this.momentArr[0] = momentStart;
      this.momentArr[1] = momentEnd;
      this.queryData();
    },

    rangePicker() {
      return this.momentArr;
    },

    reset() {
      this.selectParkId = [];
      this.momentArr = [];
      thsi.invoiceNo = ""
      this.queryData();
    },

    getQueryCondition() {
      let condition = this.queryCondition;
      let startTimeStamp = "";
      let endTimeStamp = "";
      condition.pID = this.selectParkId || [];
      if (this.momentArr != undefined && this.momentArr.length != 0) {
        condition.timeScreenCondition = "6";
        startTimeStamp = new Date(this.momentArr[0]).getTime() / 1000;
        endTimeStamp = new Date(this.momentArr[1]).getTime() / 1000;
      } else {
        condition.timeScreenCondition = "0";
      }
      condition.startTimeStamp = startTimeStamp;
      condition.endTimeStamp = endTimeStamp;
      // condition.invoiceNo=this.invoiceNo;
      return condition;
    },

    /* ---------------- 维度变化 -------------- */
    onChange(date) {
      this.selectId = -1;
      this.momentArr = date;
    },
    onOk() {
      this.selectId = -1;
      this.queryData();
    },
    selectParkChange() {
      this.queryData();
    },
    /* 停车点编号改变 */
    invoiceNoChange() {
      this.queryCondition.invoiceNo = this.invoiceNo;
      this.queryData();
    },
    /* ---------------- 停车点 ---------------- */
    initParkList() {
      CommonApi.getParkList()
        .then((data) => {
          this.parks = data.data;
        })
        .catch((err) => {
          console.log("error:", err);
        });
    },

    /* ---------------- 查询 ---------------- */
    queryData() {
      let condition = this.getQueryCondition();
      Invoice.getInvoiceList(condition)
        .then((data) => {
          let { list, total, pageNum, pageSize } = data.data;
          let array = list || [];
          array = array.map((item, index) => {
            return { ...item, no: total - (pageNum - 1) * pageSize - index };
          });
          this.dataSource = array;
          this.pagination.total = total;
          this.pagination.current = pageNum;
        })
        .catch((error) => {
          console.log("获取停车记录数据异常！", error);
        });
    },
    nowTime() {
      let yy = new Date().getFullYear();
      var mm =
        new Date().getMonth() < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      var dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
    },
    getTimeDifference(startTime, endTime) {
      // let timeData={}
      var timeStr = "";
      if (startTime != null) {
        let sd = startTime.substring(0, 19).replace(/-/g, "/"); // 将时间字符串截取到秒，并将其中的-换成/
        let se = ""; // 这是定义结束时间，如果为空，就获取当前时间
        let cdate = new Date();
        if (endTime != null || endTime != "") {
          se = endTime.substring(0, 19).replace(/-/g, "/"); // 将时间字符串截取到秒，并将其中的-换成/
        } else {
          se = cdate.getTime();
        }
        let sde = new Date(se).getTime() - new Date(sd).getTime(); // 将时间字符转成时间戳
        if (sde > 1) {
          // 当有差值时，就计算
          let d = (sde / 1000 / 60 / 60 / 24 + "").split("."); // 这是获取h d
          if (Number(d[0]) != null && Number(d[0]) != "") {
            timeStr = timeStr + Number(d[0]) + "天";
          }
          if (d.length > 1) {
            if (Math.floor(Number("0." + d[1]) * 24) > 0) {
              timeStr = timeStr + Math.floor(Number("0." + d[1]) * 24) + "小时";
            }
          }
          let c = (sde / 1000 / 60 / 60 + "").split("."); // 这是获取min
          if (c.length > 1) {
            if (Math.floor(Number("0." + c[1]) * 60) > 0) {
              timeStr = timeStr + Math.floor(Number("0." + c[1]) * 60) + "分";
            }
          }
          let b = (sde / 1000 / 60 + "").split("."); // 这是获取s
          if (b.length > 1) {
            if (Math.floor(Number("0." + b[1]) * 60) > 0) {
              timeStr = timeStr + Math.floor(Number("0." + b[1]) * 60) + "秒";
            }
          }
        }
      }
      return timeStr;
    },

    /* ---------------- 表格 ---------------- */
    customRow(record) {
      return {
        on: {
          // 事件
          click: () => {
            this.currRowData = record;
            this.tableState.rowId = record.id;
          }, // 点击行
          dblclick: () => {
            this.showCorrectionPopup(record);
          },
        },
      };
    },

    setRowClassName(record) {
      return record.id === this.tableState.rowId ? "clickRowStyl" : "";
    },

    /* ---------------- 表单功能 ---------------- */
    exportExcel() {
      let condition = this.getQueryCondition();
      invoice
        .exportExcel(condition)
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          link.href = URL.createObjectURL(blob);
          var fileName = decodeURIComponent(res.headers.filename);
          if (fileName == null || fileName == "undefined") {
            fileName = "发票信息.xlsx";
          }
          link.style.display = "none";

          link.setAttribute("download", `${fileName}`);
          link.click();
        })
        .catch((err) => {
          console.log("error");
          console.log(err);
          let data = err.data;
          if (data) {
            return this.$message.warn(data);
          }
        });
    },

    /* ---------------- 标题展开 ---------------- */
    switchExpend() {
      this.isExpand = !this.isExpand;
    },

    /* ---------------- 车牌纠正弹窗 ---------------- */
    showCorrectionPopup(item) {
      console.log(item);
      let { pdfUrl } = item;
      this.correctPopupData.visible = true;
      let imageList = [];
      console.log(pdfUrl);
      if (pdfUrl) {
        imageList.push(pdfUrl);
      }

      this.correctPopupData.imageList = imageList;
      this.correctPopupData.loading = false;
      // this.correctPopupData.id = id;
    },

    hideCorrectionPopup() {
      this.correctPopupData.visible = false;
    },

    commitCorrect() {
      this.hideCorrectionPopup();
    },

    cancelCorrect() {
      this.hideCorrectionPopup();
    },
    delayedTime() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(this.invoiceNoChange, 800);
    },
  },

  /*计算层*/
  computed: {
    computedStyle() {
      return function (selectId) {
        return this.selectId == selectId ? "" : "";
      };
    },

    expendStyle() {
      return this.isExpand ? "" : "height: 150px; overflow: hidden;";
    },
    // computedDue() {
    //     let dataSource = this.dataSource || [];
    //     let result = 0;
    //     dataSource.forEach(item => {
    //         result += isNaN(parseInt(item.shouldMoney)) ? 0 : parseInt(item.shouldMoney);
    //     })
    //     return result / 100;
    // },
    //  computedDueR() {
    //     let dataSource = this.dataSource || [];
    //     let result = 0;
    //     dataSource.forEach(item => {
    //         result += isNaN(parseInt(item.realityMoney)) ? 0 : parseInt(item.realityMoney);
    //     })
    //     return result / 100;
    // },
  },

  /*渲染层*/
  mounted() {
    this.button_time(0);
    this.initParkList();
  },
};
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
}

.header-setting {
  position: relative;
  width: 100%;
  height: auto;
  background: #fff;
  padding-bottom: 40px;
}

.header-setting .breadcrumb {
  margin-left: 41px;
  padding-top: 15px;
}

/* 展开 */
.box-expand {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  /* text */
  cursor: pointer;
  line-height: 40px;
  font-size: 15px;
  text-align: center;
  color: #020202;
  background: white;
}

/*表格行选中背景颜色*/
.clickRowStyl {
  background-color: #c1e0fd;
}

.box-condition-body {
  padding-top: 15px;
}

.box-condition-item {
  display: flex;
  align-items: center;
  min-width: 1500px;
  padding: 10px 0;
}

.box-condition-item .box-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 5px 20px 5px;
}

.button_time button {
  margin-left: 10px;
}

/* 表单 */
.box-form {
  padding-left: 40px;
  padding-right: 40px;
  min-height: 705px;
  background: #fff;
  margin-top: 8px;
}

.box-form .box-tool {
  padding-top: 11px;
  margin: 8px 0;
  width: 100%; /* flex */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* box-correction-popup */
.box-correction-popup {
  padding: 20px;
  height: 555px;
  /* flex */
  display: flex;
  align-items: center;
}

.box-correction-popup .box-image {
  padding: 0 15px;
  width: 888px;
  height: 500px;
}

.box-correction-popup .box-image .icon-image {
  width: 100%;
  height: 100%;
}

.box-correction-popup .box-correct {
  margin: 0 15px;
  width: 310px;
  height: 500px;
}

.box-correction-popup .box-correct .item-correct {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.box-correction-popup .box-correct .item-correct .text-correct {
  font-weight: 300;
  font-size: 14px;
  width: 100px;
}

.box-correction-popup .box-correct .item-correct .text-value {
  font-weight: 300;
  font-size: 14px;
  line-height: 1.428571429;
  color: #020202;
}
</style>
